package com.huangguolin.cloud.spring.security;

import com.huangguolin.cloud.login.entity.loginUserEntity;
import com.huangguolin.cloud.login.service.LoginService;
import com.huangguolin.cloud.mybatis.entity.PtUserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class GdmtUserDetailsService implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private LoginService loginService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        PtUserEntity ptUserEntity = loginService.queryUserInfoByName(userName);
        if(ptUserEntity == null){
            throw new UsernameNotFoundException(userName + "do not axit");
        }
        //String password = passwordEncoder.encode("654321");
        List<GrantedAuthority> collection = new ArrayList<>();
        List<String> authlist = loginService.queryAuthListById(ptUserEntity.getUserUuid());
        for (String authItem:authlist){
            collection.add(new SimpleGrantedAuthority("ROLE_" + authItem));
        }
//        collection.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
//        collection.add(new SimpleGrantedAuthority("ROLE_USER_UPDATE"));
          collection.add(new SimpleGrantedAuthority("ROLE_TEST1"));
//        collection.add(new SimpleGrantedAuthority("ROLE_TEST1_ADD"));
        // 参数分别是：用户名，密码，用户权限
        loginUserEntity user = new loginUserEntity(ptUserEntity, collection);

        return user;
    }
}
